import React, { useEffect } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, Flex } from 'antd';
import { loginApi } from '../../http/http';
import { useDispatch } from "react-redux"

import request from '../../request/request';
import { setuse } from '../../reducers/useSlice';
import useDebunse from '../../hooks/useDebunse';

const Login = () => {
  let [form] = Form.useForm()
  let xinxi = useDispatch()
  const onFinish = useDebunse(async (values) => {
    console.log('Received values of form: ', values);

    const res = await loginApi(values)
    const { code, token, } = res.data
    if (code == 1) {
      alert('登录成功')
      localStorage.setItem('token', token)
      localStorage.setItem('username', values.username)

      if (values.remember) {
        localStorage.setItem('use', values.username)
        localStorage.setItem('pas', values.password)
      }
      else {
        localStorage.removeItem('use')
        localStorage.removeItem('pas')
      }

      let res = await request({ url: '/getUserInfo', method: 'get', data: values })
      console.log(res);
      xinxi(setuse({ name: res.data.data.name, pic: res.data.data.pic }))
      window.location.href = '/index/home'
    }

  }, 800);

  useEffect(() => {
    form.setFieldsValue({
      username: localStorage.getItem('use'),
      password: localStorage.getItem('pas')
    })
  }, [])


  return (
    <Form
      form={form}
      name="login"
      initialValues={{ remember: true }}
      style={{ maxWidth: 360 }}
      onFinish={onFinish}
    >
      <Form.Item
        name="username"
        rules={[{ required: true, message: 'Please input your Username!' }]}
      >
        <Input prefix={<UserOutlined />} placeholder="Username" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: 'Please input your Password!' }]}
      >
        <Input prefix={<LockOutlined />} type="password" placeholder="Password" />
      </Form.Item>
      <Form.Item>
        <Flex justify="space-between" align="center">
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>Remember me</Checkbox>
          </Form.Item>
          <a href="">Forgot password</a>
        </Flex>
      </Form.Item>
      <Form.Item shouldUpdate>
        {() => (
          <Button
            type="primary"
            htmlType="submit"
            disabled={

              !form.isFieldsTouched(true) ||
              !!form.getFieldsError().filter(({ errors }) => errors.length).length
            }
          >
            登录
          </Button>
        )}
      </Form.Item>
    </Form>
  );
};
export default Login;